package com.retail.lottery.colalottery.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

public class RequestParamUtils {
    public static Map<String, Object> getAllParams(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();

        // 1. 获取 GET 查询参数 或 POST 表单参数
        request.getParameterMap().forEach((key, values) -> {
            if (values.length == 1) {
                params.put(key, values[0]);
            } else {
                params.put(key, Arrays.asList(values));
            }
        });

        // 2. 如果是 POST + JSON 请求，解析 Body
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            String contentType = request.getContentType();
            if (contentType != null && contentType.contains("application/json")) {
                try {
                    String body = request.getReader().lines().collect(Collectors.joining());
                    if (!body.isEmpty()) {
                        ObjectMapper mapper = new ObjectMapper();
                        Map<String, Object> jsonParams = mapper.readValue(body, Map.class);
                        params.putAll(jsonParams);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return params;
    }
}
